import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap";
import axios from "axios";
import "./index.css";

const params = new URLSearchParams(window.location.search);
const title = document.getElementById("title");
const content = document.getElementById("content");

axios.get(`${import.meta.env.BASE_URL}/${params.get('hash')}.json`).then(response => {
    document.title = title.innerText = response.data.title;
    const head = Object.values(response.data.mapping).find(item => item.message === undefined);
    let key = head.children[0];
    while (key !== undefined) {
        let item = response.data.mapping[key];
        key = (Array.isArray(item.children) && item.children.length === 1) ? item.children[0] : undefined;
        if (item.message['author'] === undefined || item.message['author']['role'] === 'system') {
            continue;
        }
        const div = document.createElement("div");
        div.innerText = item.message.content['parts'][0];
        if (item.message['author']['role'] === 'assistant') {
            div.classList.add("message", "receiver-message");
            item = response.data.mapping[key];
            if (item !== undefined && item.message['author']['role'] === 'assistant') {
                div.innerText += item.message.content['parts'][0];
                key = (Array.isArray(item.children) && item.children.length === 1) ? item.children[0] : undefined;
            }
        } else if (item.message['author']['role'] === 'user') {
            div.classList.add("message", "sender-message");
        }
        content.appendChild(div);
    }
}).catch(err => window.location.href = '/404.html');